﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Ex5.SearchForString
{
    class SearchForString
    {
        private static void Traverse(string path, string textToFind)
        {
            try
            {
                string[] files = Directory.GetFiles(path);

                foreach (string fileName in files.Where(f => f.EndsWith(".txt")))
                {
                    using (StreamReader reader = File.OpenText(fileName))
                    {
                        FileStream resultStream = new FileStream("..\\..\\result.txt", FileMode.Append);
                        using (StreamWriter writer = new StreamWriter(resultStream))
                        {
                            int lineNumber = 0;
                            string line;
                            while ((line = reader.ReadLine()) != null)
                            {
                                lineNumber++;
                                if (line.IndexOf(textToFind) > -1)
                                {
                                    writer.WriteLine("Folder: [{0}]", path);
                                    writer.WriteLine("File Name: {0}",fileName);
                                    writer.WriteLine("Line Number: {0}", lineNumber);
                                    writer.WriteLine("Line Content: {0}\n", line);
                                    break;
                                }
                            }
                        }
                    }
                }
                string[] subdirs = Directory.GetDirectories(path);
                foreach (string subdir in subdirs)
                {
                    Traverse(subdir, textToFind);
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Can not access directory: {0}", path);
            }
        }

        static void Main(string[] args)
        {
            string dirName = "..\\..\\TestFolder";
            string textToFind = "file";


            string resultFileDir = "..\\..\\result.txt";
            File.Create(resultFileDir).Dispose();

            Traverse(dirName, textToFind);
        }
    }
}
